package org.example.studentsystem_back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.studentsystem_back.common.CommonResponse;
import org.example.studentsystem_back.domain.Students;
import org.example.studentsystem_back.domain.Users;
import org.example.studentsystem_back.dto.PageDTO;
import org.example.studentsystem_back.mapper.UsersMapper;
import org.example.studentsystem_back.service.StudentsService;
import org.example.studentsystem_back.mapper.StudentsMapper;
import org.example.studentsystem_back.util.JwtUtil;
import org.example.studentsystem_back.vo.dataCenterVo.StudentDataCenterVo.*;
import org.example.studentsystem_back.vo.studentMangeVo.StudentsVo;
import org.example.studentsystem_back.vo.studentMangeVo.UpdateStudentVo;
import org.example.studentsystem_back.vo.userManageVo.PageLeaderVo;
import org.example.studentsystem_back.vo.userManageVo.PageStudentVo;
import org.example.studentsystem_back.vo.userManageVo.smallVo.PageStudentItem;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author Lenovo
* @description 针对表【students】的数据库操作Service实现
* @createDate 2024-07-09 16:58:53
*/
@Service
public class StudentsServiceImpl extends ServiceImpl<StudentsMapper, Students>
    implements StudentsService{
    @Resource
    StudentsMapper studentsMapper;
    @Resource
    UsersMapper usersMapper;
    @Override
    public CommonResponse<StudentsVo> getCurrentStudents(HttpServletRequest request) {
        String token=request.getHeader("token");
        JwtUtil.verifyToken(token);
        Users user= JwtUtil.getCurrentUser(token);
        QueryWrapper<Students> studentsQueryWrapper = new QueryWrapper<>();
        if (user != null) {
            studentsQueryWrapper.eq("userId",user.getUserid());
        }
        Students student = studentsMapper.selectOne(studentsQueryWrapper);
        if(student==null)
        {
            return CommonResponse.createForSuccess("没有学生信息",null);
        }
        StudentsVo studentsVo = studentToStudentVo(student, user);
        return CommonResponse.createForSuccess("查询成功",studentsVo);
    }

    @Override
    public CommonResponse<StudentsVo> getStudentByUserId(String userId) {
        QueryWrapper<Students>studentsQueryWrapper=new QueryWrapper<>();
        studentsQueryWrapper.eq("userId",userId);
        Students student = studentsMapper.selectOne(studentsQueryWrapper);
        if(student == null)
        {
            return CommonResponse.createForSuccess("没有该userId的学生信息",null);
        }
        Users user = usersMapper.selectById(userId);
        StudentsVo studentsVo = studentToStudentVo(student,user);
        return CommonResponse.createForSuccess("查询成功",studentsVo);
    }

    @Override
    public CommonResponse<StudentsVo> addStudent(Students student) {
        QueryWrapper<Students> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("student_id",student.getStudentId());

        Users user = usersMapper.selectById(student.getUserid());

        if(studentsMapper.selectList(queryWrapper).isEmpty())
        {
            studentsMapper.insert(student);
            StudentsVo studentsVo=studentToStudentVo(student,user);

            return CommonResponse.createForSuccess("添加成功",studentsVo);
        }
        return CommonResponse.createForError("该studentId已存在");
    }

    @Override
    public CommonResponse<UpdateStudentVo> updateStudent(String userId,UpdateStudentVo updateStudentVo) {
        QueryWrapper<Students> studentsQueryWrapper = new QueryWrapper<>();
        studentsQueryWrapper.eq("userId",userId);
        Students old_student = studentsMapper.selectOne(studentsQueryWrapper);
        old_student.setAddress(updateStudentVo.getAddress());
        old_student.setBirthdate(updateStudentVo.getBirthdate());
        old_student.setPhone(updateStudentVo.getPhone());
        old_student.setEmail(updateStudentVo.getEmail());
        studentsMapper.updateById(old_student);
        Users user = usersMapper.selectById(userId);
        return CommonResponse.createForSuccess("修改成功",updateStudentVo);
    }

    @Override
    public CommonResponse<StudentsVo> deleteStudent(String studentId) {
        Students student = studentsMapper.selectById(studentId);
        Users user = usersMapper.selectById(student.getUserid());
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("userId",student.getUserid());
        QueryWrapper<Students> studentsQueryWrapper = new QueryWrapper<>();
        studentsQueryWrapper.eq("student_id",studentId);
        studentsMapper.delete(studentsQueryWrapper);
        StudentsVo studentsVo = studentToStudentVo(student,user);
        return CommonResponse.createForSuccess("删除成功",studentsVo);
    }



    private StudentsVo studentToStudentVo(Students students, Users users){
        StudentsVo studentsVo = new StudentsVo();
        studentsVo.setStudentId(students.getStudentId());
        studentsVo.setUserid(students.getUserid());
        studentsVo.setClassName(students.getClassName());
        studentsVo.setMajor(students.getMajor());
        studentsVo.setDepartment(students.getDepartment());
        studentsVo.setPhone(students.getPhone());
        studentsVo.setHukou(students.getHukou());
        studentsVo.setAddress(students.getAddress());
        studentsVo.setType(students.getType());
        studentsVo.setEducation(students.getEducation());
        studentsVo.setBirthdate(students.getBirthdate());
        studentsVo.setPoliticalStatus(students.getPoliticalStatus());
        studentsVo.setNationality(students.getNationality());
        studentsVo.setEmail(students.getEmail());
        studentsVo.setIdCard(students.getIdCard());
        studentsVo.setPassword(users.getPassword());
        studentsVo.setName(users.getName());
        studentsVo.setGender(users.getGender());
        studentsVo.setRole(users.getRole());

        return studentsVo;
    }

    private UpdateStudentVo studentToUpdateStudentVo(Students student){
        UpdateStudentVo updateStudentVo = new UpdateStudentVo();
        updateStudentVo.setAddress(student.getAddress());
        updateStudentVo.setBirthdate(student.getBirthdate());
        updateStudentVo.setEmail(student.getEmail());
        updateStudentVo.setPhone(student.getPhone());
        return updateStudentVo;
    }

    @Override
    public CommonResponse<PageStudentVo> getAllStudentsByPage(PageDTO pageDTO) {
        Page<Students> studentsPage=new Page<>(pageDTO.getPage(), pageDTO.getLimit());
        List<Students> studentsList = studentsMapper.selectPage(studentsPage,null).getRecords();
        Long total = studentsMapper.selectCount(null);

        List<PageStudentItem> itemList = new ArrayList<>();
        studentsList.forEach((student -> {
            PageStudentItem item = new PageStudentItem();
            item.setDataByStudent(student);
            item.setName(usersMapper.selectById(student.getUserid()).getName());
            itemList.add(item);
        }));

        PageStudentVo pageStudentVo = new PageStudentVo();
        pageStudentVo.setPageList(itemList);
        pageStudentVo.setTotal(total);


        return CommonResponse.createForSuccess("查询成功", pageStudentVo);
    }
    @Override
    public CommonResponse<StudentDataCenterVo> getStudentDataCenter(){
        List<Students> studentsList = studentsMapper.selectList(null);
        StudentDataCenterVo studentDataCenterVo = new StudentDataCenterVo();
        /*学历部分*/
        List<EducationDataVo> educationDataVoList = new ArrayList<>();

        EducationDataVo undergraduateDataVo = new EducationDataVo();
        EducationDataVo masterDataVo = new EducationDataVo();
        EducationDataVo doctorDataVo = new EducationDataVo();
        System.out.println(educationDataVoList);

        for(int i = 0; i < 3; i++){
            if(i == 0){
                undergraduateDataVo = educationDataToVo(undergraduateDataVo,"本科");
                System.out.println(undergraduateDataVo);
                educationDataVoList.add(undergraduateDataVo);
                System.out.println(educationDataVoList);
            }else if(i == 1){
                masterDataVo = educationDataToVo(masterDataVo,"硕士");
                System.out.println(masterDataVo);
                educationDataVoList.add(masterDataVo);
                System.out.println(educationDataVoList);
            }else {
                doctorDataVo = educationDataToVo(doctorDataVo,"博士");
                System.out.println(doctorDataVo);
                educationDataVoList.add(doctorDataVo);
                //Collections.addAll(educationDataVoList, undergraduateDataVo, masterDataVo, doctorDataVo);
                System.out.println(educationDataVoList);
            }
        }

        studentDataCenterVo.setEducationData(educationDataVoList);
        /*学历部分*/

        /*籍贯部分*/
        //统计籍贯种类
        NationalityDataVo nationalityDataVo = new NationalityDataVo();
        List<String> placeList = new ArrayList<>();
        List<Integer> valueList = new ArrayList<>();
        for(Students student : studentsList) {
            String place = student.getNationality();
            placeList.add(place);
        }
        Set<String> set = new HashSet<>(placeList);
        placeList = new ArrayList<>(set);
        nationalityDataVo.setPlaceList(placeList);
        //籍贯人数
        for (String placeItem : placeList){
            QueryWrapper<Students> numOfPlaceQueryWrapper = new QueryWrapper<>();
            numOfPlaceQueryWrapper.eq("nationality",placeItem);
            int numOfPlace = Math.toIntExact(studentsMapper.selectCount(numOfPlaceQueryWrapper));
            valueList.add(numOfPlace);
        }
        nationalityDataVo.setValueList(valueList);

        studentDataCenterVo.setNationalityData(nationalityDataVo);
        /*籍贯部分*/

        /*政治身份*/
        List<PoliticalDataVo> politicalDataVoList = new ArrayList<>();

        for(int i = 0; i < 3; i++){
            if(i == 0){
                PoliticalDataVo politicalDataVo = politicalDataToVo("共青团员");
                politicalDataVoList.add(politicalDataVo);
            }else if(i == 1){
                PoliticalDataVo politicalDataVo = politicalDataToVo("群众");
                politicalDataVoList.add(politicalDataVo);
            }else {
                PoliticalDataVo politicalDataVo = politicalDataToVo("党员");
                politicalDataVoList.add(politicalDataVo);
            }
        }
        studentDataCenterVo.setPoliticalData(politicalDataVoList);

        /*政治身份*/

        /*专业部分*/
        List<MajorDataVo> majorDataVoList = new ArrayList<>();
        List<String> majorList = new ArrayList<>();
        for(Students student : studentsList){
            String major = student.getMajor();
            majorList.add(major);
        }
        Set<String> majorSet = new HashSet<>(majorList);
        majorList = new ArrayList<>(majorSet);

        for(String major : majorList){
            QueryWrapper<Students> majorQueryWrapper = new QueryWrapper<>();
            majorQueryWrapper.eq("major",major);
            int num = Math.toIntExact(studentsMapper.selectCount(majorQueryWrapper));
            MajorDataVo majorDataVo = new MajorDataVo();
            majorDataVo.setName(major);
            majorDataVo.setValue(num);
            majorDataVoList.add(majorDataVo);
        }
        studentDataCenterVo.setMajorData(majorDataVoList);
        /*专业部分*/

        /*学院部分*/
        List<CollegeDataVo> collegeDataVoList = new ArrayList<>();
        List<String> collegeDataList = new ArrayList<>();
        for(Students student : studentsList){
            String college = student.getDepartment();
            collegeDataList.add(college);
        }
        Set<String> collegeSet = new HashSet<>(collegeDataList);
        collegeDataList = new ArrayList<>(collegeSet);

        for(String college : collegeDataList){
            QueryWrapper<Students> collegeQueryWrapper = new QueryWrapper<>();
            collegeQueryWrapper.eq("department",college);
            int num = Math.toIntExact(studentsMapper.selectCount(collegeQueryWrapper));
            CollegeDataVo collegeDataVo = new CollegeDataVo();
            collegeDataVo.setName(college);
            collegeDataVo.setValue(num);
            collegeDataVoList.add(collegeDataVo);
        }
        studentDataCenterVo.setCollegeData(collegeDataVoList);
        /*学院部分*/

        return CommonResponse.createForSuccess("查询成功",studentDataCenterVo);
    }

    private EducationDataVo educationDataToVo(EducationDataVo educationDataVo,String education){
        int num = 0;

        QueryWrapper<Students> undergraduateQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Students> masterQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Students> doctorQueryWrapper = new QueryWrapper<>();
        switch (education){
            case "本科":
                undergraduateQueryWrapper.eq("education",education);
                num = Math.toIntExact(studentsMapper.selectCount(undergraduateQueryWrapper));
                break;
            case "硕士":
                masterQueryWrapper.eq("education",education);
                num = Math.toIntExact(studentsMapper.selectCount(masterQueryWrapper));
                break;
            case "博士":
                doctorQueryWrapper.eq("education",education);
                num = Math.toIntExact(studentsMapper.selectCount(doctorQueryWrapper));
                break;
            default:
                break;
        }

        educationDataVo.setName(education);
        educationDataVo.setValue(num);

        return educationDataVo;
    }

    private PoliticalDataVo politicalDataToVo(String political_status){
        PoliticalDataVo politicalDataVo = new PoliticalDataVo();
        QueryWrapper<Students> politicalQueryWrapper = new QueryWrapper<>();
        politicalDataVo.setName(political_status);
        politicalQueryWrapper.eq("political_status",political_status);
        int num = Math.toIntExact(studentsMapper.selectCount(politicalQueryWrapper));
        politicalDataVo.setValue(num);
        return  politicalDataVo;
    }
}





